<template>
	<div class="cms-document-editor-container">
		<el-card shadow="hover" class="h100">
			<el-row :gutter="35">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
					<center>
						<Editor :config="editor.config"></Editor>
					</center>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10" style="border-left: 1px solid #DDDDDD;">
					<el-form ref="addDocumentFormRef" :model="formData" :rules="formRules" label-width="80px">
						<el-row :gutter="35">
							<el-col class="mb20">
								<div v-show="isFormHide">
									<el-upload ref="documentUploadRef" list-type="picture-card" 
										:limit="upload.limit"
										:accept="upload.accept"
										:auto-upload="false"
										:disabled="readonly"
										:action="upload.action"
										:headers="upload.headers"
										:name="upload.name"
										:file-list="upload.images"
										:before-upload="handleBeforeUpload"
										:on-change="handleUploadChange"
										:on-exceed="handleUploadExceed"
										:on-preview="handleUploadPreview"
										:on-success="handleUploadSuccess"
										:on-remove="handleUploadRemove">
										<el-icon><plus /></el-icon>
										<template #tip>
											<div class="el-upload__tip color-danger">
												最多允许上传{{upload.limit}}张图片附件，允许图片格式有{{upload.accept}}，
												您还可以从正文<el-botton style="cursor: pointer;" class="el-upload__tip color-primary" type="primary" link @click="onPickerImage">提取图片</el-botton>为附件。
											</div>
										</template>
									</el-upload>
									<el-dialog v-model="upload.dialogVisible">
										<img class="w100" :src="upload.picture" alt="" />
									</el-dialog>
								</div>
							</el-col>
							<el-col class="mb10">
								<el-row :gutter="35">
									<el-col v-show="isFormHide">
										<el-form-item label="标题" prop="title">
											<el-input v-model="formData.title" placeholder="请输入稿件标题" :readonly="readonly" clearable></el-input>
										</el-form-item>
									</el-col>
									<el-col v-show="isFormHide">
										<el-form-item label="副标题" prop="subtitle">
											<el-input v-model="formData.subtitle" placeholder="请输入稿件副标题" :readonly="readonly" clearable></el-input>
										</el-form-item>
									</el-col>
									<el-col v-show="isFormHide">
										<el-form-item label="摘要" prop="docAbstract">
											<el-input type="textarea" v-model="formData.docAbstract" placeholder="请输入摘要" :readonly="readonly" clearable></el-input>
										</el-form-item>
									</el-col>
									<el-col v-show="isFormHide">
										<el-form-item label="关键字" prop="docKeywords">
											<div style="white-space: pre-line;">
												<el-tag v-for="(tag, index) in formData.docKeywords?.split(',')" :key="index"
													class="ml5" closable :disable-transitions="true" 
													@close="onDocKeywordClose(tag)" >{{ tag }}</el-tag>
												<el-input v-if="docKeywordVisible" ref="docKeywordRef" v-model="docKeyword" 
													class="ml5"
													size="small"
													@keyup.enter="onDocKeywordConfirm"
													@blur="onDocKeywordConfirm"
												/>
												
												<el-button v-else class="button-new-tag ml5" size="small" @click="docKeywordVisible = true">
													+ 关键字
												</el-button>
											</div>
											<!-- <el-input v-model="formData.docKeywords" placeholder="请输入稿件关键字,多个关键字请用英文逗号 , 分割" :readonly="readonly" clearable></el-input> -->
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-show="isFormHide">
										<el-form-item label="责任编辑" prop="docAuthor">
											<el-input v-model="formData.docAuthor" placeholder="请输入责任编辑" :readonly="readonly" clearable></el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-show="isFormHide">
										<el-form-item label="稿件类型" prop="docType">
											<el-select v-model="formData.docType" placeholder="请选择稿件类型" :disabled="readonly" clearable class="w100">
												<el-option label="图文稿" value="0"></el-option>
												<el-option label="音频稿" value="1"></el-option>
												<el-option label="视频稿" value="2"></el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-show="isFormHide">
										<el-form-item label="撰写时间" prop="writeTime">
											<el-date-picker v-model="formData.writeTime" type="datetime" placeholder="请选择撰写时间" :readonly="readonly" class="w100"/>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-show="isFormHide">
										<el-form-item label="稿件排序" prop="orderNum">
											<el-input-number v-model="formData.orderNum" :min="0" :max="999" clearable :disabled="readonly" class="w100"></el-input-number>
										</el-form-item>
									</el-col>
									<el-col v-show="isFormHide">
										<el-form-item label="原文链接" prop="writeTime">
											<el-input v-model="formData.originalHttpUrl" placeholder="请输入原文链接http://或https://" :readonly="readonly" clearable></el-input>
										</el-form-item>
									</el-col>
									<el-col v-show="isFormHide">
										<el-form-item label="备注" prop="remark">
											<el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" :readonly="readonly" clearable></el-input>
										</el-form-item>
									</el-col>
								</el-row>
							</el-col>
							<el-col>
								<center>
									<el-button icon="el-icon-close" @click="onCancel">关 闭</el-button>
									<!-- <el-button v-if="isFormHide == false" icon="el-icon-arrow-down" @click="onFormOpen">展 开</el-button> -->
									<!-- <el-button v-if="isFormHide == true" icon="el-icon-arrow-up" @click="onFormHide">隐 藏</el-button> -->
									<!-- 状态 = 初稿|未通过|已撤销 -> 保存 -->
									<el-button v-auths="['cms:document:add', 'cms:document:edit']" type="primary" icon="el-icon-check" 
										v-if="formData.docStatus == 0 || formData.docStatus == 3 || formData.docStatus == 7"
										@click="onSubmit">保 存</el-button>
									<!-- 预览 -->
									<el-button type="primary" icon="el-icon-search" v-if="formData.id != null" @click="onOpenPreviewDocument">预 览</el-button>
									<!-- 状态 = 初稿|未通过|已撤销 -> 待审核 -->
									<el-button v-auth="'cms:document:auth'"  type="primary" icon="el-icon-finished"
										v-if="formData.id && (formData.docStatus == 0 || formData.docStatus == 3 || formData.docStatus == 7)"
										@click="onAuthDocument">提 审</el-button>
									<!-- 状态 = 待审核|未通过 -> 已通过 -->
									<el-button v-auth="'cms:document:allowed'" type="primary" icon="el-icon-circle-check" 
										v-if="formData.docStatus == 1 || formData.docStatus == 3"
										@click="onAllowedDocument">通 过</el-button>
									<!-- 状态 = 待审核|已通过 -> 未通过 -->
									<el-button v-auth="'cms:document:refused'" type="primary" icon="el-icon-circle-close" 
										v-if="formData.docStatus == 1 || formData.docStatus == 2"
										@click="onRefusedDocument">驳 回</el-button>
									<!-- 状态 = 已通过 -> 发布 -->
									<el-button v-auth="'cms:document:released'" type="primary" icon="el-icon-collection-tag" 
										v-if="formData.docStatus == 2"
										@click="onReleasedDocument">发 布</el-button>
									<!-- 状态 = 已通过 -> 定时发布 -->
									<el-button v-auth="'cms:document:timing'" type="primary" icon="el-icon-alarm-clock" 
										v-if="formData.docStatus == 2"
										@click="onTimingDocument">定时发布</el-button>
									<!-- 状态 = 已发布|发布失败 -> 重新发布 -->
									<el-button v-auth="'cms:document:released'" type="primary" icon="el-icon-refresh-right"
										v-if="formData.docStatus == 5 || formData.docStatus == 9"
										@click="onReleasedDocument">重新发布</el-button>
									<!-- 状态 = 待发布|已发布|定时发布 -> 撤销发布 -->
									<el-button v-auth="'cms:document:revoked'" type="primary" icon="el-icon-refresh-left" 
										v-if="formData.docStatus == 4 || formData.docStatus == 5 || formData.docStatus == 8"
										@click="onRevokedDocument">撤销发布</el-button>
									<!-- 状态 = 所有 -> 删除 -->
									<el-button v-auth="'cms:document:remove'" v-if="formData.id" type="danger" icon="el-icon-delete" 
										@click="onDelDocument">删 除</el-button>
								</center>
							</el-col>
						</el-row>
					</el-form>
				</el-col>
			</el-row>
		</el-card>
		<SelectTemplate ref="selectTemplateRef"></SelectTemplate>
		<SelectTimer ref="selectTimerRef" @submit="onCancel"></SelectTimer>
		<CropperDialog ref="cropperDialogRef" :model="cropper.options" @submit="onCropperDialogSubmit" @cancel="onCropperDialogCancel"/>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRoute } from 'vue-router';
import { Session } from '/@/utils/storage';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { auths } from '/@/utils/authFunction';
import { Plus } from '@element-plus/icons-vue';
import Editor from '/@/components/135editor/index.vue';
import SelectTemplate from '/@/views/cms/document/component/selectTemplate.vue';
import SelectTimer from '/@/views/cms/document/component/selectTimer.vue';
import CropperDialog from '/@/views/cms/material/cropper/index.vue';
import { getSiteConfig } from '/@/api/cms/channel/index';
import { addDocument, editDocument, getDocument, delDocument, authDocument, allowedDocument, refusedDocument, releasedDocument, revokedDocument } from '/@/api/cms/document/index';
import { uploadServer, uploadConfig, uploadPicture } from '/@/api/cms/helper/index';
export default {
	name: 'cms/document/editor',
	components: { Plus, Editor, SelectTemplate, SelectTimer, CropperDialog },
	setup() {
		const route = useRoute();
		const { proxy } = getCurrentInstance() as any;
		const addDocumentFormRef = ref();
		const documentUploadRef = ref();
		const selectTemplateRef = ref();
		const selectTimerRef = ref();
		const cropperDialogRef = ref();
		const state = reactive({
			isFormHide: true,
			readonly: false,
			siteconfig: {},
			docKeywordVisible: false,
			docKeyword: '',
			formData: {
				siteId: '',
				channelId: '',
				docKeywords: null,
				htmlContent: '',
				picture: '',
				pictures: [],
				docType: '0',
				docStatus: 0,
				orderNum: 1
			},
			formRules: {
				title: { required: true, message: '稿件标题不能为空', trigger: 'blur' }
			},
			editor: {
				config: {
					serverUrl: uploadServer(),
					configUrl: uploadConfig(),
					catchRemoteImageEnable: true,
				}
			},
			upload: {
				action: uploadPicture(),
				limit: 9,
				accept: '.svg,.webp,.gif,.jpg,.png,.jpeg',
				headers: { Authorization: 'Bearer ' + Session.get('token') },
				name: 'upload',
				images: [],
				dialogVisible : false
			},
			cropper: {
				options: {
					aspectRatio: 0,
				}
			}
		});
		
		const loadSiteConfig = (siteId: string) => {
			getSiteConfig({'siteId': siteId}).then((res) => {
				if(res.code == 0 && res.data){
					state.siteconfig = res.data;
					state.editor.config.serverUrl = uploadServer() + '&sitecode=' + state.siteconfig?.siteCode;
					state.upload.action = uploadPicture() + '&sitecode=' + state.siteconfig?.siteCode;
				}
			});
		}
		
		// 加载稿件信息
		const loadDocument = async (docId: String) => {
			if(docId){
				await getDocument({id: docId}).then(res => {
					if(res.code == 0){
						state.formData = res.data;
						if(state.formData.pictures){
							state.formData.pictures.forEach(url => state.upload.images.push({'url': url}));
						}
						//处理稿件时间格式
						if(state.formData.writeTime){
							state.formData.writeTime = new Date(state.formData.writeTime);
						}
						//处理稿件读写权限
						readyDocument();
					}
				});
			}
		}
		
		const readyDocument = () => {
			setTimeout(()=>{
				if(window.current_editor){
					window.current_editor?.ready(() => {
						window.current_editor?.setContent(state.formData.htmlContent);
					})
					//如果没有编辑和修改权限，不允许修改
					if(!auths(['cms:document:add', 'cms:document:edit'])){
						state.readonly = true;
						window.current_editor?.setDisabled();
					}
					//如果稿件状态 != 初稿|拒绝|下架状态，不允许修改
					if(state.formData.docStatus != 0 && state.formData.docStatus != 3 && state.formData.docStatus != 7){
						state.readonly = true;
						window.current_editor?.setDisabled();
					}
				}else{
					//编辑器实例重试
					readyDocument();
				}
			}, 500);
		}
		
		const closeDialog = (row?: object) => {
			proxy.mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
		};
		
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 新增
		const onSubmit = () => {
			addDocumentFormRef.value.validate(valid => {
				if(valid){
					let htmlContent = window.current_editor?.getContent();
					if(htmlContent.length <= 0){
						ElMessage.warning('稿件正文不能为空');
						return;
					}
					let params = {
						siteId: state.formData.siteId,
						channelId: state.formData.channelId,
						docType: state.formData.docType || '0',//默认是图文稿
						title: state.formData.title,
						subtitle: state.formData.subtitle,
						docAbstract: state.formData.docAbstract,
						docKeywords: state.formData.docKeywords,
						docAuthor: state.formData.docAuthor,
						writeTime: state.formData.writeTime ? formatDate(state.formData.writeTime, 'yyyy-MM-dd HH:mm:ss') : null,
						originalHttpUrl: state.formData.originalHttpUrl,
						orderNum: state.formData.orderNum,
						remark: state.formData.remark,
						htmlContent: htmlContent,
						pictures: state.formData.pictures,
					}
					if(state.formData.id){
						params.id = state.formData.id;
						editDocument(params).then((res) => {
							if(res.code === 0){
								ElMessage.success('保存成功');
								state.formData = res.data;
								//处理时间格式
								if(state.formData.writeTime){
									state.formData.writeTime = new Date(state.formData.writeTime);
								}
							}
						});
					}else{
						addDocument(params).then((res) => {
							if(res.code === 0){
								ElMessage.success('保存成功');
								state.formData = res.data;
								//处理时间格式
								if(state.formData.writeTime){
									state.formData.writeTime = new Date(state.formData.writeTime);
								}
							}
						});
					}
					
				}
			});
		};
		const onFormOpen = () => {
			state.isFormHide = true;
		}
		const onFormHide = () => {
			state.isFormHide = false;
		}
		const onAuthDocument = () => {
			ElMessageBox.confirm('确定提审稿件吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				authDocument({ids: [state.formData.id]}).then((res) => {
					if(res.code === 0){
						ElMessage.success('操作成功');
						closeDialog();
					}
				});
			}).catch(() => {});
		}
		const onAllowedDocument = () => {
			ElMessageBox.confirm('确定通过稿件提审吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				allowedDocument({ids: [state.formData.id]}).then((res) => {
					if(res.code === 0){
						ElMessage.success('操作成功');
						closeDialog();
					}
				});
			}).catch(() => {});
		}
		const onRefusedDocument = () => {
			ElMessageBox.confirm('确定拒绝稿件提审吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				refusedDocument({ids: [state.formData.id]}).then((res) => {
					if(res.code === 0){
						ElMessage.success('操作成功');
						closeDialog();
					}
				});
			}).catch(() => {});
		}
		const onReleasedDocument = () => {
			ElMessageBox.confirm('确定发布稿件吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				releasedDocument({ids: [state.formData.id]}).then((res) => {
					if(res.code === 0){
						ElMessage.success('操作成功');
						closeDialog();
					}
				});
			}).catch(() => {});
		}
		const onTimingDocument = () => {
			selectTimerRef.value.openDialog(state.formData);
		}
		const onRevokedDocument = () => {
			ElMessageBox.confirm('确定撤销发布稿件吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				revokedDocument({ids: [state.formData.id]}).then((res) => {
					if(res.code === 0){
						ElMessage.success('操作成功');
						closeDialog();
					}
				});
			}).catch(() => {});
		}
		const onDelDocument = () => {
			ElMessageBox.confirm('确定删除稿件吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				delDocument({ids: [state.formData.id]}).then((res) => {
					if(res.code === 0){
						ElMessage.success('操作成功');
						closeDialog();
					}
				});
			}).catch(() => {});
		}
		const onOpenPreviewDocument = () => {
			if(state.formData.id){
				selectTemplateRef.value.openDialog(state.formData);
			}else{
				ElMessage.warning('请先保存稿件，再预览');
			}
		}
		//上传之前
		const handleBeforeUpload = (file) => {
			state.upload.headers.Authorization = 'Bearer ' + Session.get('token');
		}
		//文件状态改变时
		const handleUploadChange = (file) => {
			if(file.status == 'ready') {
				const ext = file.name.substring(file.name.lastIndexOf('.'));
				if(file.size > 0 && state.upload.accept.indexOf(ext) != -1){
					cropperDialogRef.value.openDialog(file);
				}else{
					ElMessage.warning('请选择' + state.upload.accept + '格式的图片');
				}
			}
		}
		const handleUploadExceed = () => {
			ElMessage.warning('最多允许上传9张封面图片');
		}
		//上传中
		const handleUploadPreview = (file) => {
			if(file.url){
				state.upload.dialogVisible = true;
				state.upload.picture = file.url;
			}
		};
		//上传成功
		const handleUploadSuccess = (res, file) => {
			if(res.state == 'SUCCESS' && res.url){
				file.url = res.url;
				state.formData.pictures.push(res.url);
			}
		};
		//移除
		const handleUploadRemove = (file) => {
			let index = state.formData.pictures.indexOf(file.url);
			if(index > -1){
				state.formData.pictures.splice(index, 1);
			}
		};
		const onCropperDialogSubmit = (file, base64) => {
			const newFile = base64ToFile(base64, file.name);
			documentUploadRef.value.handleRemove(file);
			documentUploadRef.value.handleStart(newFile);
			documentUploadRef.value.submit();
		}
		const onCropperDialogCancel = (file) => {
			documentUploadRef.value.handleRemove(file);
		}
		//将base64转换为文件
		const base64ToFile = (base64, filename) => { 
			var arr = base64.split(','),
			mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]),
			n = bstr.length,
			u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new File([u8arr], filename, {type: mime});
		}
		const onDocKeywordConfirm = () => {
			if (state.docKeyword) {
				const keywords = state.formData.docKeywords?.split(',') || [];
				keywords.push(state.docKeyword);
				state.formData.docKeywords = keywords?.join(',');
			}
			state.docKeywordVisible = false
			state.docKeyword = '';
		}
		const onDocKeywordClose = (tag: string) => {
			const keywords = state.formData.docKeywords?.split(',') || [];
			keywords.splice(keywords.indexOf(tag), 1);
			state.formData.docKeywords = keywords?.length > 0 ? keywords?.join(',') : null;
		}
		//从正文提取图片s
		const onPickerImage = () => {
			let UE = window.UE || {};
			let imgs = UE.dom?.domUtils?.getElementsByTagName(window.current_editor?.document, "img");
			for (let i = 0, ci; (ci = imgs[i++]);) {
				let url = ci.getAttribute('_src') || ci.getAttribute('src') || ci.src;
				if(url){
					state.formData.pictures.push(url);
					state.upload.images.push({'url': url});
				}
			}
		}
		// 页面加载时
		onMounted(() => {
			state.formData.siteId = route.query.siteId;
			state.formData.channelId = route.query.channelId;
			loadSiteConfig(route.query.siteId);
			loadDocument(route.query.id);
		});
		
		return {
			addDocumentFormRef,
			documentUploadRef,
			selectTemplateRef,
			selectTimerRef,
			cropperDialogRef,
			onCancel,
			onFormOpen,
			onFormHide,
			onSubmit,
			onAuthDocument,
			onAllowedDocument,
			onRefusedDocument,
			onReleasedDocument,
			onTimingDocument,
			onRevokedDocument,
			onDelDocument,
			onOpenPreviewDocument,
			handleBeforeUpload,
			handleUploadChange,
			handleUploadExceed,
			handleUploadPreview,
			handleUploadSuccess,
			handleUploadRemove,
			onCropperDialogSubmit,
			onCropperDialogCancel,
			onDocKeywordConfirm,
			onDocKeywordClose,
			onPickerImage,
			...toRefs(state),
		};
	}
}
</script>
